from shlex import join

from flask import Flask,render_template,request,escape
from geo import *
import numpy as np

KEY = "8066ec0cc0d0913d5d385f8693a88128"
app = Flask(__name__)
def log_request(req:'flask_request',response:str) -> None:
    with open('gaode.log','a') as log:
        print(req.form,req.remote_addr,req.user_agent,response,file=log,sep='|')
        #print(str(dir(req)),response,file=log)

def get_data(response):
    """
    清理数据
    :param response: 还未清理的数据
    :return:
    """
    df = pd.json_normalize(response['route']['paths'][0]['steps'])[
        ['instruction', 'orientation', 'distance', 'duration', 'action']]

    # 首先将pandas读取的数据转化为array
    data_array = np.array(df)
    # 然后转化为list形式
    data_list = data_array.tolist()
    return data_list

@app.route('/',methods=["get","post"])
def nav():
    if request.method == "GET":
        return render_template("main.html")
    else:
        return render_template("index.html")


@app.route('/index',methods=["get","post"])
def index():
    """
    GET:用户get请求返回输入起点终点界面
    POST:返回数据清理后的页面
    :return:
    """
    if request.method == "GET":
        return render_template("index.html")
    else:
        start = request.form["start"]
        end = request.form["end"]
        start_code = geocode(KEY,start)
        end_code = geocode(KEY,end)
        response = car_path(KEY, start_code, end_code)

        print(response)
        data_list = get_data(response)  # 清理后的数据
        log_request(request,response)
        return render_template("show.html",data_list=data_list)

#步行路径查询
@app.route('/walk',methods=["get","post"])
def walk_way():
    key = key1_key
    if request.method == "GET":
        return render_template("walk.html")
    else:
        start = request.form["start"]
        end = request.form["end"]
        start_code = geocode(KEY,start)
        end_code = geocode(KEY,end)
        response = walk_path(key,start_code,end_code)
        #print(response)
        data_list = pd.json_normalize(response)['instruction']
        data_array = np.array(data_list)
        # 然后转化为list形式
        data_list = data_array.tolist()
        #print(data_list)
        log_request(request, response)
        return render_template("show_walk.html", data_list=data_list)

#访问记录
@app.route('/viewlog')
def view_the_log() -> 'html':
    contents = []
    with open('gaode.log') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))
    titles = ('表单数据','远程机器的IP地址','web识别字符串','调用结果')
    return render_template('viewlog.html',
                           the_title = '日志系统',
                           the_row_titles = titles,
                           the_data = contents,)


if __name__ == '__main__':
    app.run(debug=True)
